package com.example.juc;

import java.util.HashMap;
import java.util.Map;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class WirterReadLockTest {
   public static void main(String[] args) {
        MyData myData = new MyData();
        for (Integer i = 0; i < 4; i++) {
            Integer temp =i;
            new Thread(() -> {
                myData.write(temp.toString());
            },i.toString()).start();
        }

        for (Integer i = 0; i < 4; i++) {
            Integer temp=i;
            new Thread(() -> {
             myData.readData(temp.toString());
            },i.toString()).start();
        }

    }
}
class MyData{
//    ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    volatile Map<String,Object> map=new HashMap<String,Object>();
    public void readData(String msg){
        this.reentrantReadWriteLock.readLock().lock();
        try {
            System.out.println("读取数据"+map.get(msg));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            this.reentrantReadWriteLock.readLock().unlock();
        }
    }
    public String write(String msg){
        reentrantReadWriteLock.writeLock().lock();
        try {
            map.put(msg,msg);
            System.out.println("准备数据"+msg);
            System.out.println("写入数据"+msg);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
            return msg;
        }
    }
}
